import 'package:flutter/material.dart';

import '../model/health_record.dart';
import '../service/database_service.dart';
import 'base_record_dialog.dart';

class AddSleepRecordDialog extends BaseRecordDialog {
  const AddSleepRecordDialog({Key? key, required String babyId})
    : super(key: key, babyId: babyId);

  @override
  _AddSleepRecordDialogState createState() => _AddSleepRecordDialogState();
}

class _AddSleepRecordDialogState
    extends BaseRecordDialogState<AddSleepRecordDialog> {
  TimeOfDay? startTime;
  TimeOfDay? endTime;

  @override
  String getDialogTitle() => '记录睡眠';

  @override
  Widget buildCustomContent(BuildContext context) {
    return Column(
      children: [
        ListTile(
          title: Text('开始时间'),
          trailing: TextButton(
            child: Text(startTime?.format(context) ?? '选择时间'),
            onPressed: () async {
              final time = await showTimePicker(
                context: context,
                initialTime: TimeOfDay.now(),
              );
              if (time != null) {
                setState(() => startTime = time);
              }
            },
          ),
        ),
        ListTile(
          title: Text('结束时间'),
          trailing: TextButton(
            child: Text(endTime?.format(context) ?? '选择时间'),
            onPressed: () async {
              final time = await showTimePicker(
                context: context,
                initialTime: TimeOfDay.now(),
              );
              if (time != null) {
                setState(() => endTime = time);
              }
            },
          ),
        ),
      ],
    );
  }

  int _calculateDuration() {
    if (startTime == null || endTime == null) return 0;
    final startMinutes = startTime!.hour * 60 + startTime!.minute;
    final endMinutes = endTime!.hour * 60 + endTime!.minute;
    return endMinutes > startMinutes
        ? endMinutes - startMinutes
        : (24 * 60 - startMinutes) + endMinutes;
  }

  @override
  Future<void> saveRecord(BuildContext context) async {
    if (startTime == null || endTime == null) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('请选择开始和结束时间')));
      return;
    }

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.sleep,
          timestamp: selectedDateTime,
          data: {
            'startTime': startTime!.format(context),
            'endTime': endTime!.format(context),
            'duration': _calculateDuration(),
            'notes': notes,
          },
        ),
      );
      Navigator.pop(context);
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
    }
  }
}
